<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="params.username" placeholder="用户名" style="width: 200px;" class="filter-item" clearable @keyup.enter.native="fetchData" />
      <el-input v-model="params.realName" placeholder="姓名" style="width: 200px;margin-left: 10px;" class="filter-item" clearable @keyup.enter.native="fetchData" />
      <el-select v-model="params.roleId" class="filter-item" style="margin-left: 10px;" placeholder="角色">
        <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
      </el-select>
      <el-select v-model="params.status" class="filter-item" style="margin-left: 10px;" placeholder="状态">
        <el-option key="0" label="正常" :value="0" />
        <el-option key="1" label="停用" :value="1" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="fetchData">
        搜索
      </el-button>
      <el-button type="success" icon="el-icon-warning-outline" class="filter-item" @click="resetForm()">重置</el-button>

    </div>
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-edit" @click="editOrAdd(0,0)">
        添加
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"

      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="用户名">
        <template slot-scope="scope">
          {{ scope.row.username }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="scope">
          {{ scope.row.realName }}
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status==0">启用</span>
          <span v-if="scope.row.status==1">停用</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作">
        <template slot-scope="scope">
          <el-row>

            <el-button type="text" @click="editOrAdd(1,scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status===1" type="text" @click="updateStatus(scope.row.id)">启用</el-button>
            <el-button v-if="scope.row.status===0" type="text" @click="updateStatus(scope.row.id)">停用</el-button>
            <el-button v-if="scope.row.rid!=='001'" type="text" @click="deleteUser(scope.row.id)">删除</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="params.page" :limit.sync="params.pageSize" @pagination="fetchData" />

    <el-dialog :title="dialogTitles[dialogIndex]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="adminData" label-width="80px" style="margin-left:50px;margin-right: 50px">
        <el-form-item label="角色" prop="rid">
          <el-select v-model="adminData.rid" class="filter-item" placeholder="角色" style="width: 100%">
            <el-option v-for="item in roleList" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminData.username" :disabled="dialogIndex===1" />
        </el-form-item>

        <el-form-item label="姓名" prop="realName">
          <el-input v-model="adminData.realName" />
        </el-form-item>

        <el-form-item v-if="adminData.id" label="密码" prop="password">
          <el-input v-model="adminData.password" show-password />
        </el-form-item>

        <el-form-item v-if="!adminData.id" label="密码" prop="password">
          <el-input v-model="adminData.password" show-password />
        </el-form-item>
        <!--<el-form-item label="地址">
          &lt;!&ndash;          <Calendar :type="0" ref="area" @changeValue="changeArea" :disable="disable"></Calendar>&ndash;&gt;
          <el-select v-model="adminData.locationCode" placeholder="请选择地址" class="townItem" style="width: 100%">
            <el-option
              v-for="item in optionsTown"
              :key="item.listKey"
              :label="item.listValue"
              :value="item.listKey"
            />
          </el-select>

        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">
          取消
        </el-button>
        <el-button type="primary" @click="save">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, roleList, deleteUser, addUser, updateStatus } from '@/api/admin'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import Calendar from '@/components/Cascader'
import { nowPassword } from '../../utils/constant'
export default {
  components: { Pagination, Calendar },
  directives: { waves },
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.dialogIndex === 1) {
        // 编辑时密码可为空
        callback()
      }
      if (!value) {
        return callback(new Error('请输入密码'))
      } else if (!(/^.{8,32}$/.test(value))) {
        return callback(new Error('有效长度为8~32个字符'))
      } else if (!(nowPassword.test(value))) {
        return callback(new Error('必须包含字母、数字、符号中至少2种'))
      } else {
        callback()
      }
      callback()
    }
    return {
      disable: false,
      list: [],
      listLoading: true,
      total: 10,
      dialogTitles: ['添加', '编辑'],
      dialogIndex: 0,
      dialogFormVisible: false,

      adminData: {

      },
      params: {
        page: 1,
        pageSize: 10,
        username: '',
        realName: ''
      },
      rules: {
        rid: [{ required: true, message: '请选择角色', trigger: 'change' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        locationCode: [{ required: true, message: '请选择地址', trigger: 'change' }]
      },
      roleList: []
    }
  },
  created() {
    this.fetchData()
    this.initRoles()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getList(this.params).then(response => {
        this.total = response.total
        this.list = response.rows

        this.listLoading = false
      })
    },
    cancel() {
      // this.$refs.area.clearCheckedNodes();
      this.dialogFormVisible = false
    },
    changeArea(vaule) {
      console.log(vaule)
      this.adminData.provinceCode = vaule[0]
      this.adminData.cityCode = vaule[1]
      this.adminData.countyCode = vaule[2]
    },
    initRoles() {
      roleList().then(res => {
        this.roleList = res
      })
    },
    editOrAdd(index, item) {
      this.adminData = Object.assign({}, item)
      delete this.adminData.provinceCode
      delete this.adminData.cityCode
      delete this.adminData.countyCode
      this.rules.password[0].required = true
      if (index === 1) {
        this.rules.password[0].required = false
        delete this.adminData.createTime
        delete this.adminData.statusString
        delete this.adminData.name
      }
      this.dialogIndex = index
      this.dialogFormVisible = true
      console.log(this.adminData)

      var areas = []
      areas[0] = item.provinceCode
      areas[1] = item.cityCode
      areas[2] = item.countyCode

      this.$nextTick(() => {
        // 初始化省市县数据
      /*  if(areas.length>0){
          this.$refs.area.initArea("-1", areas);
        }else{
          this.$refs.area.initArea("-1", []);
        }*/

        this.$refs['dataForm'].clearValidate()
      })
    },
    save() {
      if (this.adminData.locationCode == -1) {
        this.adminData.locationCode = ' '
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addUser(this.adminData).then(res => {
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: this.dialogTitles[this.dialogIndex] + '成功!'
            })
            this.fetchData()
          })
        }
      })
    },
    updateStatus(id) {
      updateStatus(id).then(res => {
        this.$message({
          type: 'success',
          message: '成功!'
        })
        this.fetchData()
      })
    },
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUser(id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.fetchData()
        })
      })
    },
    resetForm() {
      this.params = {
        page: 1,
        pageSize: 10
      }
      this.$nextTick(() => {
        this.fetchData()
      })
    }
  }
}
</script>
